using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Resources;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Windows.Markup;
using System.Text.RegularExpressions;

namespace SilverlightSnoop
{
    public class XapAssembly
    {
        internal Xap _Xap;

        public string Name
        {
            get
            {
                return Assembly.FullName;
            }
        }

        public Assembly Assembly { get; private set; }

        public List<XapAssemblyType> Types
        {
            get
            {
                return _Types;
            }
        }
        private List<XapAssemblyType> _Types;

        public List<ResourceDictionary> MergedAppLevelDictionaries
        {
            get
            {
                return _MergedAppLevelDictionaries;
            }
        }
        private List<ResourceDictionary> _MergedAppLevelDictionaries = new List<ResourceDictionary>();

        private void BuildApplicationResourceDictionaryPaths()
        {
            _MergedAppLevelDictionaries.Clear();

            string asmName = Assembly.ToString().Substring(0, Assembly.ToString().IndexOf(','));
            Uri loadUri = new Uri(String.Format("/{0};component/app.xaml", asmName), UriKind.RelativeOrAbsolute);
            var appXamlResourceStream = Application.GetResourceStream(loadUri);

            if (appXamlResourceStream == null)
                return;

            var appXamlStream = appXamlResourceStream.Stream;

            StreamReader reader = new StreamReader(appXamlStream);
            String xaml = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            var appXaml = XmlReader.Create(new StringReader(xaml));

            List<String> importedRDs = new List<string>();

            Regex rex = new Regex("xmlns:([a-zA-Z]|[0-9])*\\s?=\\s?\".*\"");
            var matches = rex.Match(xaml);
            foreach (Match item in rex.Matches(xaml))
            {
                if (item.Value.Contains("http://schemas.microsoft.com/winfx/2006/xaml"))
                    continue;
                var toAdd = item.Value;

                if (!toAdd.Contains("assembly="))
                {
                    string[] ns = toAdd.Replace("\"", "").Split(new String[] { "=" }, StringSplitOptions.None);
                    String nsPrefix = ns[0].Split(':')[1] + ":";
                    String nsName = ns[1].Split(':')[1];

                    var startPos = xaml.IndexOf(nsPrefix);

                    if(startPos == -1)
                        continue;

                    int typeToFindIndex = xaml.IndexOf(nsPrefix, startPos);
                    if(typeToFindIndex == -1)
                        continue;

                    var match = Regex.Match(xaml.Substring(typeToFindIndex), String.Format("{0}[a-zA-Z0-9]*", nsPrefix));
                    
                    if(match == null || match.Groups.Count == 0)
                        continue;

                    var type = nsName + "." + match.Value;

                    foreach (var asm in _Xap.LoadedAssemblies)
                    {
                        if (asm.GetType(type) != null)
                        {
                            toAdd.Remove(toAdd.Length - 1);
                            toAdd += ";assembly=" + asm.FullName + "\"";
                            importedRDs.Add(toAdd);
                            break;
                        }
                    }

                    continue;
                }

                importedRDs.Add(toAdd);
            }
                        

            while (appXaml.Read())
            {
                if (appXaml.IsStartElement("ResourceDictionary"))
                {
                }
                else if (appXaml.IsStartElement("Application.Resources"))
                {

                    string appResourcesHeader = "<Application.Resources>";
                    string endResourcesHeader = "</Application.Resources>";
                    int startResources = xaml.IndexOf(appResourcesHeader);
                    int endResources = xaml.IndexOf(endResourcesHeader);
                    String splitResources = xaml.Substring(startResources + appResourcesHeader.Length);
                    splitResources = splitResources.Remove(splitResources.IndexOf(endResourcesHeader));

                    string header = "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"";
                    foreach (var item in importedRDs)
                    {

                        header += "\n" + item;
                    }
                    header += ">";
                    string footer = "</ResourceDictionary>";

                    while (true)
                    {
                        if (!appXaml.Read())
                            break;

                        if (!appXaml.IsStartElement("ResourceDictionary"))
                            continue;

                        appXaml.MoveToAttribute("Source");

                        if (!appXaml.ReadAttributeValue())
                            continue;

                        ResourceDictionary dict = new ResourceDictionary();
                        Uri source = new Uri(appXaml.Value, UriKind.RelativeOrAbsolute);
                        dict.Source = source;
                        _MergedAppLevelDictionaries.Add(dict);
                    }

                    int startRD = splitResources.IndexOf("<ResourceDictionary.MergedDictionaries>");
                    string rdMergedEndTag = "</ResourceDictionary.MergedDictionaries>";
                    int endRD = splitResources.IndexOf(rdMergedEndTag) + rdMergedEndTag.Length;

                    if (startRD != -1 && endRD != -1)
                    {
                        splitResources = splitResources.Remove(startRD, endRD - startRD);
                    }

                    splitResources = splitResources.Replace("<ResourceDictionary>", "");
                    splitResources = splitResources.Replace("</ResourceDictionary>", "");

                    var split = splitResources.Split(new String[] { rdMergedEndTag }, StringSplitOptions.None);

                    // This removes all the stupid Blend tags
                    splitResources = Regex.Replace(splitResources, "d:[a-zA-Z0-9]*=\"[\\w\\s\\.\\,]*\"", String.Empty);

                    ResourceDictionary toAdd = (ResourceDictionary)XamlReader.Load(header + splitResources + footer);
                    _MergedAppLevelDictionaries.Insert(0, toAdd);
                    //Application.Current.Resources.MergedDictionaries.Insert(0, toAdd);
                }
            }
        }

        internal Type bootStrapApp = null;

        /// <summary>
        /// Initializes a new instance of the XapAssembly structure.
        /// </summary>
        public XapAssembly(Assembly assembly, Xap xapAssembly)
        {

            _Xap = xapAssembly;

            _Types = new List<XapAssemblyType>();
            Assembly = assembly;


            //System.Diagnostics.Debug.WriteLine("Assembly: {0}", Name);
            foreach (var item in assembly.GetTypes())
            {
                //System.Diagnostics.Debug.WriteLine("   Type found: {0}", item.FullName);

                if (item.IsSubclassOf(typeof(System.Windows.Application)))
                    bootStrapApp = item;

                if (!item.IsSubclassOf(typeof(FrameworkElement)))
                    continue;

                Types.Add(new XapAssemblyType(item, this));
            }
            BuildApplicationResourceDictionaryPaths();

        }
    }
}
